package com.xinziruo.richclient.support;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.executor.ExecutorFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.xinziruo.richclient.support.codec.CommandProtocolDecoder;
import com.xinziruo.richclient.support.codec.CommandProtocolEncoder;
import com.xinziruo.richclient.support.command.Command;


/**
 * 
 * @author loudyn
 * 
 */
public class CommandClientBroker {
	private IoSession session;

	/**
	 * 
	 * @param host
	 * @param port
	 */
	public CommandClientBroker(String host, int port, IoHandler handler) {

		NioSocketConnector connector = new NioSocketConnector();
		DefaultIoFilterChainBuilder fcBuilder = connector.getFilterChain();
		fcBuilder.addLast("command-codec-filter", new ProtocolCodecFilter(new CommandProtocolEncoder(), new CommandProtocolDecoder()));
		fcBuilder.addLast(
							"executor", 
							new ExecutorFilter(Executors.newFixedThreadPool(50))
						);

		connector.setHandler(handler);
		ConnectFuture future = connector.connect(new InetSocketAddress(host, port));
		future.awaitUninterruptibly();
		if (!future.isConnected()) {
			throw new IllegalStateException("Cann't connect to the server!");
		}

		this.session = future.getSession();

	}

	public void writeCommand(Command comm) {
		this.session.write(comm);
	}

	public void close() {
		this.session.close(true);
	}
}
